//Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections.Generic;
using System.Text;

namespace Eas.WebCrawler.PlugIns.RequestComparers
{
    /// <summary>Prioritizes all requests based on whether or not they come from a specified host.  Additional prioritization occurs through an inner <see cref="BaseComparer"/>.</summary>
    public class SpecificHostComparer : BaseRequestDesirabilityComparer
    {
        private string _HostName;
        private bool _PreferToStayOnHost;

        /// <summary>Whether or not to prioritize requests to the specified host above (<code>true</code>) or below(<code>false</code>) other request.</summary>
        public bool PreferToStayOnHost
        {
            get { return _PreferToStayOnHost; }
        }

        /// <summary>The name of the target host.</summary>
        /// <remarks>This includes the whole host name includeing the 'www.' part and the '.com' part).</remarks>
        /// <example>www.ggogle.com</example>
        public string HostName
        {
            get { return _HostName; }
        }

        /// <summary>Constructs a <see cref="SpecificHostComparer"/> from the name of the target host, whether or not to prefer requests to the target host and the inner comparer to use for ties.</summary>
        /// <param name="hostName">The target host's name.</param>
        /// <param name="preferToStayOnHost">Whether or not to prioritize requests to the specified host above (<code>true</code>) or below(<code>false</code>) other request.</param>
        /// <param name="innerComparer">The inner host who breaks ties in priority.</param>
        public SpecificHostComparer(string hostName, bool preferToStayOnHost, BaseComparer innerComparer)
            : base(innerComparer)
        {
            _HostName = hostName;
            _PreferToStayOnHost = preferToStayOnHost;
        }

        /// <summary>Returns whether or not the current request comes from a high-priority host.</summary>
        /// <param name="request">The request to check.</param>
        /// <returns><code>true</code> if the request is being made to a high priority host, or <code>false</code> otherwise.</returns>
        public override bool IsPreferred(Eas.WebCrawler.Interfaces.Request request)
        {
            if (_PreferToStayOnHost)
                return request.Uri.Host == _HostName;
            else
                return request.Uri.Host != _HostName;
        }
    }
}
